import Document, { Html, Head, Main, NextScript } from 'next/document'
import CommonScript from '../components/CommonScript'
import AppConfig, { Favicon, BaiduSiteVerification } from '@/config'
import { StyleProvider, createCache, extractStyle } from '@ant-design/cssinjs'
import type { DocumentContext } from 'next/document'

const { keywords, description } = AppConfig

class MyDocument extends Document {
  static async getInitialProps(ctx: any) {
    const initialProps = await Document.getInitialProps(ctx)
    return { ...initialProps }
  }

  render() {
    return (
      <Html>
        <Head>
          <link rel="shortcut icon" type="image/x-icon" href={Favicon} />
          <meta name="keywords" content={keywords} />
          <meta name="description" content={description} />
          <meta name="baidu-site-verification" content={BaiduSiteVerification} />
          <CommonScript />
        </Head>
        <body className="light dark:bg-night version-1">
          <Main />
          <NextScript />
        </body>
      </Html>
    )
  }
}

MyDocument.getInitialProps = async (ctx: DocumentContext) => {
  const cache = createCache()
  const originalRenderPage = ctx.renderPage
  ctx.renderPage = () => originalRenderPage({
    enhanceApp: (App: any) => (props: any) => (
      <StyleProvider cache={cache}>
        <App {...props} />
      </StyleProvider>
    ),
  })

  const initialProps = await Document.getInitialProps(ctx)
  const style = extractStyle(cache, true)
  return {
    ...initialProps,
    styles: (
      <>
        {initialProps.styles}
        <style dangerouslySetInnerHTML={{ __html: style }} />
      </>
    ),
  }
}

export default MyDocument
